﻿



    using System;
    using Microsoft.Extensions.Logging;
    using log4net;
    using log4net.Repository;
    using System.Reflection;
    using System.IO;

namespace CKS2320.Common.Utils
{ 
    public class Log4NetProvider : ILoggerProvider
    {
        private readonly ILoggerRepository _loggerRepository;

        public Log4NetProvider(string configFile)
        {
            _loggerRepository = LogManager.CreateRepository(
                Assembly.GetEntryAssembly(),
                typeof(log4net.Repository.Hierarchy.Hierarchy));

            log4net.Config.XmlConfigurator.Configure(_loggerRepository, new FileInfo(configFile));
        }

        public ILogger CreateLogger(string categoryName)
        {
            return new Log4NetLogger(LogManager.GetLogger(_loggerRepository.Name, categoryName));
        }

        public void Dispose()
        {
            // Cleanup if necessary
        }
    }

    public class Log4NetLogger : ILogger
    {
        private readonly ILog _logger;

        public Log4NetLogger(ILog logger)
        {
            _logger = logger;
        }

        public IDisposable BeginScope<TState>(TState state) => null;

        public bool IsEnabled(LogLevel logLevel)
        {
            return logLevel switch
            {
                LogLevel.Trace => _logger.IsDebugEnabled,
                LogLevel.Debug => _logger.IsDebugEnabled,
                LogLevel.Information => _logger.IsInfoEnabled,
                LogLevel.Warning => _logger.IsWarnEnabled,
                LogLevel.Error => _logger.IsErrorEnabled,
                LogLevel.Critical => _logger.IsFatalEnabled,
                _ => false,
            };
        }

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel)) return;

            var message = formatter(state, exception);
            switch (logLevel)
            {
                case LogLevel.Trace:
                case LogLevel.Debug:
                    _logger.Debug(message, exception);
                    break;
                case LogLevel.Information:
                    _logger.Info(message, exception);
                    break;
                case LogLevel.Warning:
                    _logger.Warn(message, exception);
                    break;
                case LogLevel.Error:
                    _logger.Error(message, exception);
                    break;
                case LogLevel.Critical:
                    _logger.Fatal(message, exception);
                    break;
            }
        }
    }

}
